package org.ainlolcat.ainscience.column.threshold;

import org.ainlolcat.ainscience.column.Column;
import org.jdom.Element;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author ainlolcat
 *         Date: 5/5/13
 */
public class ThresholdHelper {

    public Threshold parse(Element element){
        String thrsType = element.getAttributeValue("type");
        String thrsMore = element.getAttributeValue("more");
        String thrsLess = element.getAttributeValue("less");
        String delta = element.getAttributeValue("delta");
        String formula = element.getAttributeValue("formula");
        boolean filter =  element.getAttributeValue("filter") == null? false : Boolean.parseBoolean(element.getAttributeValue("filter"));
        boolean local =  element.getAttributeValue("local") == null? false : Boolean.parseBoolean(element.getAttributeValue("local"));

        int thrsTypeInt = thrsType.equals("WARNING")? Threshold.WARRNING : Threshold.CRITICAL;
        if (thrsMore!=null){
            return new MoreThanThreshold(thrsTypeInt, Double.parseDouble(thrsMore), filter, local).setFormula(formula);
        }
        if (thrsLess!=null){
            return new LessThanThreshold(thrsTypeInt, Double.parseDouble(thrsLess), filter, local).setFormula(formula);
        }
        if (delta!=null){
            if (delta.endsWith("%")){
                return new PercentDeltaThreshold(thrsTypeInt, Double.parseDouble(delta.substring(0, delta.length() - 1))/100, filter, local).setFormula(formula);
            } else {
                return new DeltaThreshold(thrsTypeInt, Double.parseDouble(delta), filter, local).setFormula(formula);
            }
        }
        throw new IllegalArgumentException("Unknown threshold type");
    }

    public void searchThresholdAndApply(Column column, Element columndDef){
        if (columndDef.getChild("threshold")!=null){
            List<Element> thresholds = columndDef.getChildren("threshold");
            Collection<Threshold> thrs = new ArrayList<Threshold>();
            for (Element eThreshold: thresholds){
                thrs.add(parse(eThreshold));
            }
            column.setThresholds(thrs);
        }
    }
}
